package com.my.collection.stack.v13;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by ZhongGang
 * at 2018/7/26 15:09
 */
public class NonReentrantLock implements Lock {
    private Sync sync = new Sync();

    @Override
    public void lock() {
        this.sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        this.sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return this.sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return this.sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        this.sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return this.sync.newCondition();
    }

    private static class Sync extends AbstractQueuedSynchronizer {
        private boolean locked = false;

        @Override
        protected boolean isHeldExclusively() {
            return true;
        }

        @Override
        protected boolean tryAcquire(int arg) {
            if (!locked) {
                this.locked = true;
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            this.locked = false;
            return true;
        }

        Condition newCondition() {
            return new ConditionObject();
        }
    }

}
